package cn.damong.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import cn.damong.response.Page;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * 抽象类控制器，封装几个通用方法
 * 
 * @author CodingPanda
 * @2019年5月9日 下午9:32:04
 *
 */
public abstract class AbstractController {

	public String getCookie(HttpServletRequest request, String cookieName) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length != 0) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equalsIgnoreCase(cookieName)) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

	public Page initPage(Integer page, Integer pageSize, Long totalCount) {
		if (null == page || 0 >= page) {
			page = 1;
		}
		if (null == pageSize || 0 >= pageSize) {
			pageSize = 100;
		}
		Long start = 1l * (page - 1) * pageSize;
		Long pageCount = (totalCount + pageSize - 1) / pageSize;
		return new Page(totalCount, page, pageSize, start, pageCount.intValue());
	}

	public UserAgent getUserAgent(HttpServletRequest request) {
		return UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
	}

}
